<?php


namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

class Index extends Backend
{
    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User\Index
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->field('id,nickname,avatar,mobile,money,score,pid,status')
                ->paginate($limit)->each(function($item,$key){
                    if(!empty($item['status']))
                    {
                        $pid = explode(',',$item['pid']);
                        // 是团长：直接去团长的名字 否则 在查上一级
                        $status = Db::name('user')->where('id',$pid[0])->value('status');
                        if($status == 1)
                        {
                            $item['team'] = Db::name('user')->where('id',$pid[0])->value('nickname');
                            if($status != 1 && $status != 0)
                            {
                                if(Db::name('user')->where('id',$pid[1])->value('status') == 1)
                                {
                                    $item['team'] = Db::name('user')->where('id',$pid[1])->value('nickname');
                                }else{
                                    $item['team'] = '';
                                }
                            }
                        }
                    }else{
                        $item['team'] = '-';
                    }
                    return $item;
                });
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig("id", $this->request->param('ids'));
        return $this->view->fetch();
    }


    /*
     * 发送优惠券
     * */
    public function coupons()
    {

        // 获取用户信息
        $data = $this->request->param();
        if(Db::name('coupons')->where('id',$data['id'])->value('num') <= 0)
            $this->error(__('数量不足,请添加'));

        foreach($data['data'] as $val)
        {
            $num[] = 1;
            if(Db::name('user_coupons')->where(['user_id'=>$val,'cou_id'=>$data['id']])->count() != 0)
            {
                $this->error(__('已添加,请勿添加'));
//                $num = Db::name('user_coupons')->where(['user_id'=>$val,'cou_id'=>$data['id']])->value('num');
//                $is_up = 1;
//                $res[] = ['user_id'=>$val,'cou_id'=>$data['id'],'num'=>1 + $num,'update_time'=>time()];
            }else{
                $is_up = 0;
                $res[] = ['user_id'=>$val,'cou_id'=>$data['id'],'num'=>1,'create_time'=>time()];
            }
        }

        Db::startTrans();
        try{
            $num = array_sum($num);
            if($is_up)
            {
                Db::name('user_coupons')->where('id',$data['id'])->update($res);
            }else{
                Db::name('user_coupons')->insertAll($res);
            }
            Db::name('coupons')->where('id',$data['id'])->setDec('num',$num);
            Db::commit();
            $this->success(__('添加成功'));
        }catch(Exception $exception)
        {
            Db::rollback();
            $this->error(__('添加失败'));
        }
        
    }

}